package com.focus.xyz.core.common.listeners;

import com.focus.xyz.core.common.annotation.Task;
import com.focus.xyz.core.common.generator.DataTask;
import com.focus.xyz.core.utils.Constants;
import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener2;
import org.testng.ITestContext;
import org.testng.ITestResult;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenmeng on 2016/5/13.
 */
public class TaskFilter implements IInvokedMethodListener2{
    private static transient Logger logger = LoggerFactory.getLogger(TaskFilter.class);


    /*找到测试用例的任务注解并执行*/
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) {
        if(method.isTestMethod()){
            Task t = method.getTestMethod().getConstructorOrMethod().getMethod().getAnnotation(Task.class);
            if(t!=null){
                String[] taskName = t.taskName();
                if(taskName!=null&&taskName.length>0){
                    String[] paras = t.paras();
                    Map<String,String> pMap = new HashMap<String, String>();
                    if(paras!=null&&paras.length>0){
                        for (String s:paras){
                            String[] aa = s.split("=");
                            if(aa!= null&&aa.length==2){
                                pMap.put(aa[0],aa[1]);
                            }
                        }
                    }
                    for(String s:taskName){
                        DataTask dt = new DataTask();
                        try {
                            Map result = dt.doTask(ConfigPropInfo.DB_TYPE,s,pMap);
                            logger.info(String.format("任务：%s执行结果：%s",s,(String) result.get(Constants.FLAG)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }

    public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) {

    }

    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {

    }

    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {

    }
}
